package online.yangcloud.web.service.meta.impl;

import cn.hutool.core.util.ObjUtil;
import com.mybatisflex.core.query.QueryWrapper;
import online.yangcloud.common.annotation.TimeConsuming;
import online.yangcloud.common.common.AppConstants;
import online.yangcloud.common.enumration.YesOrNoEnum;
import online.yangcloud.common.model.business.list.ListSplitBusiness;
import online.yangcloud.common.tools.ExceptionTools;
import online.yangcloud.common.tools.ListTools;
import online.yangcloud.core.mapper.GlobalMapper;
import online.yangcloud.core.model.entity.BlockEntity;
import online.yangcloud.web.service.meta.BlockMetadataService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @author zhuboyang
 * @since 2023年06月10 22:19:03
 */
@Service
@Transactional(rollbackFor = Exception.class)
@TimeConsuming
public class BlockMetadataServiceImpl implements BlockMetadataService {

    @Resource
    private GlobalMapper globalMapper;

    @Override
    public void insertBlock(BlockEntity block) {
        int updateResult = globalMapper.acquireBlock().insertWithPk(block);
        if (updateResult == 0) {
            ExceptionTools.businessLogger();
        }
    }

    @Override
    public BlockEntity queryByHash(String hash) {
        return globalMapper.acquireBlock().selectOneByQuery(QueryWrapper.create()
                .where(BlockEntity::getHash).eq(hash)
                .and(BlockEntity::getIsDelete).eq(YesOrNoEnum.NO.code()));
    }

    @Override
    public List<BlockEntity> queryListByIds(List<String> ids) {
        return globalMapper.acquireBlock().selectListByQuery(QueryWrapper.create()
                .where(BlockEntity::getId).in(ids)
                .and(BlockEntity::getIsDelete).eq(YesOrNoEnum.NO.code()));
    }

    @Override
    public List<BlockEntity> queryListByHashList(List<String> hashList) {
        List<BlockEntity> metadata = new ArrayList<>();
        while (ObjUtil.isNotNull(hashList) && !hashList.isEmpty()) {
            ListSplitBusiness<String> business = ListTools.split(hashList, AppConstants.Batch.QUERY);
            metadata.addAll(globalMapper.acquireBlock().selectListByQuery(QueryWrapper.create()
                    .where(BlockEntity::getHash).in(business.getSplits())
                    .and(BlockEntity::getIsDelete).eq(YesOrNoEnum.NO.code())));
            hashList = business.getSources();
        }
        return metadata;
    }

}
